package com.example.demo.test;
import lombok.Data;
/**
 前序遍历：先输出父节点，然后遍历左子树，再遍历右子树
 中序遍历：先遍历左子树，然后输出父节点，再遍历右子树
 后序遍历：先遍历左子树，然后遍历右子树，再输出父节点
 */

@Data
public class Tree {
    private TreeNode root;
    //前序遍历
    public void preOrder(){
        if(this.root != null){
            this.root.preOrder();
        }else {
            System.out.println("二叉树为空");
        }
    }
    //中序遍历
    public void infixOrder(){
        if(this.root != null){
            this.root.infixOrder();
        }else {
            System.out.println("二叉树为空");
        }
    }
    //后序遍历
    public void postOrder(){
        if(this.root != null){
            this.root.postOrder();
        }else {
            System.out.println("二叉树为空");
        }
    }
    public static void main(String argsp[]){
        //创建一课二叉树
        Tree binaryTree = new Tree();
        //创建节点
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(4);
        TreeNode node4 = new TreeNode(5);
         //建立树上的节点的关系
        binaryTree.setRoot(root);
        root.setLeft(node1);
        root.setRight(node3);
        node1.setLeft(node4);
        node1.setRight(node2);
        //前序遍历
        System.out.println("前序遍历");
        binaryTree.preOrder();
        //中序遍历
        System.out.println("中序遍历");
        binaryTree.infixOrder();
        //后序遍历
        System.out.println("后序遍历");
        binaryTree.postOrder();
    }
}
@Data
class TreeNode{
    private int value;
    private TreeNode left;
    private TreeNode right;
    //构造
    public TreeNode(int value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "TreeNode{" +
                "value=" + value +
                '}';
    }
    //前序遍历
    public void preOrder(){
        //先输出父节点
        System.out.println(this);
        //递归向左子树前序遍历
        if(this.left != null){
            this.left.preOrder();
        }
        //递归向右子树前序遍历
        if(this.right != null){
            this.right.preOrder();
        }

    }

    //中序遍历
    public void infixOrder(){
        //递归向左子树中序遍历
        if(this.left != null){
            this.left.infixOrder();
        }
        //输出父节点
        System.out.println(this);
        //递归向右子树中序遍历
        if(this.right != null){
            this.right.infixOrder();
        }
    }

    //后序遍历
    public void postOrder(){
        //递归向左子树后序遍历
        if(this.left != null){
            this.left.postOrder();
        }
        //递归向右子树后序遍历
        if(this.right != null){
            this.right.postOrder();
        }
        //输出父节点
        System.out.println(this);
    }
}
